
// Norm.LastIdManager.js
// Philip Weaver philip@philmaker.com

Norm.LastIdManager = {
	
	firstPass : true,
	
	createIDTable : function() {
		Jaxer.DB.execute("CREATE TABLE IF NOT EXISTS lastidtable(table_name VARCHAR, last_id INTEGER)");
	},
	
	dropIDTable : function() {
		Jaxer.DB.execute("DROP TABLE IF EXISTS lastidtable");
	},
	
	resetTable : function(tableName) {
		
		this.firstPassCheck();
		Jaxer.DB.execute("DELETE FROM lastidtable WHERE table_name =  ?", [tableName]);
	},
	
	getLastId : function(tableName) {
		
		this.firstPassCheck();
		var resultSet = Jaxer.DB.execute("SELECT lastidtable.last_id from lastidtable WHERE lastidtable.table_name = ?", [tableName]);
		var lastID;
		if (resultSet.rows.length == 0) {
			lastID = 0;
			Jaxer.DB.execute("INSERT INTO lastidtable (table_name, last_id) values (?, ?)", [tableName, lastID]);
		} else {
			lastID = parseInt(resultSet.rows[0].$values[0]);
		}
		
		return lastID;
	},
	
	putLastId : function(tableName, lastID) {
		
		this.firstPassCheck();
		var resultSet = Jaxer.DB.execute("SELECT lastidtable.last_id FROM lastidtable WHERE lastidtable.table_name = ?", [tableName]);
		if (resultSet.rows.length == 0) {
			Norm.Database.execute("INSERT INTO lastidtable (table_name, last_id) values (?, ?)", [tableName, lastID]);
		} else {
			Norm.Database.execute("UPDATE lastidtable SET last_id = ? WHERE table_name =  ?", [lastID, tableName]);
		}
	},
	
	firstPassCheck : function() {
		
		if (this.firstPass) {
			if (false) this.dropIDTable();
			this.createIDTable();
			this.firstPass = false;
		}
	}
	
};
